//
//  SIUserAccount.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/3.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit

private let accountFile: NSString = "useraccount.json"

class SIUserAccount: NSObject {
    
    ///访问令牌
    var access_token: String?
    ///用户id
    var uid: String?
    ///令牌过期秒数 针对使用者三天,会递减
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    ///令牌到期日期 针对使用者三天
    var expiresDate: Date?
    
    ///用户昵称
    var screen_name: String?
    
    ///用户头像地址urlString
    var avatar_large: String?
    
    override var description: String {
        
        return yy_modelDescription()
    }
    
    //构造函数,懒加载时候调用
    override init() {
        super.init()
        
        guard let path = accountFile.cz_appendDocumentDir(),
            data = NSData(contentsOfFile: path),
            dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject]
            else {
               
                return
        }
        //登录与否的入口,因为本地有加载token
        yy_modelSet(with: dict ?? [:])
        
        
        ///access token过期
        if expiresDate?.compare(Date()) != .orderedDescending {
            
            print("账户过期")
            
            ///token设置为nil
            access_token = nil
            
            uid = nil
            
            ///删除用户信息
            _ = try? FileManager.default.removeItem(atPath: path)
        }
        
        print("从沙盒加载用户信息")
        
        
    }
    
    
    /// 保存数据到沙盒文档,格式是json
    func saveAccount() {
        //把模型转换成字典
        var dict = (self.yy_modelToJSONObject() as? [String: AnyObject]) ?? [:]
        //字典删去变量
        dict.removeValue(forKey: "expires_in")
        //json序列化成data
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted),
            //保存的路径
            filePath = accountFile.cz_appendDocumentDir()
            else {
                
                return
        }
        //写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户账户保存成功 \(filePath)")
        
    }

}
